import json
import re
import yaml


METHOD = 'yaml'

pattern = r'(\w+) (https?://\S+)'
urls = {}

def Cout(info:str, cnt):
    info = str(info)
    info = info.replace(',','`,')
    match = re.match(pattern, info)
    if match:
        name = match.group(1)
        url = match.group(2)
        # print(f'Name: {name}')
        # print(f'RUL: {url}')
        print("Menu, "+ str(cnt) +  ", Add, " + name  + ", MenuHandler")
        urls[name] = url
    else:
        # print('No match')
        print("Menu, "+ str(cnt) +  ", Add, " + info  + ", MenuHandler")

def SubCout(info, parent, cnt):
    info = str(info)
    info = info.replace(',','`,')
    print("Menu, "+ parent +  ", Add, " + info  + ", :" + str(cnt))

cnt = 0
add = 0

def dfs(myData, parent):
    global cnt, add
    if(not isinstance(myData, dict)):
        if(isinstance(myData, str)):
            Cout(myData, cnt)
            add = 1
        else:
            for item in myData:
                Cout(item, cnt)
                add = 1
        return cnt
    for tmpData in myData:
        SubCout(tmpData, parent, dfs(myData[tmpData], tmpData))
        if(add):
            add = 0
            cnt += 1
    return parent

def Url_add():
    for name in urls:
        # print(urls)
        print("Case \"", name, "\":\n", sep="")        
        print("run ", urls[name], sep="")

        
end1 = '''
return  ; End of script's auto-execute section.

GetClipboard(URL)
{
    clipSaved := clipboardAll
    clipboard := ;clear clipboard
    Send ^c
    sleep,100
    Transform, URL, Deref, %URL% ;为了展开字符串里面的变量
    run %URL%
    ;如果没有选中文件，将粘贴板恢复
    if(clipboard != "")
    {
        clipboard := clipSaved
    }
    clipSaved = ; free
}

MenuHandler:
Switch A_ThisMenuItem
{
Case "百度": 
    GetClipboard("https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=92765401_hao_pg&wd=%clipboard%")
Case "谷歌":
    GetClipboard("https://www.google.com/search?q=%clipboard%")
Case "博客":
    run https://mp.csdn.net/mp_blog/manage/article?
'''

end2 = '''
Default: 
    clipboard :=  A_ThisMenuItem
    Send ^v
}
return
^2::
Menu, MyMenu, Show ; 这里设置你需要定义的快捷键，这里设置的是ctrl+2
'''
if METHOD == 'yaml':
    with open("./resume.yaml", 'r', encoding='utf-8') as file:
        result = yaml.safe_load(file)
        dfs(result, "MyMenu")
        print(end1)
        Url_add()
        print(end2)

else:
    with open("./resume.json", encoding='utf-8') as f:
        result = json.load(f)
        dfs(result, "MyMenu")
        print(end1)
        Url_add()
        print(end2)


